<template>
  <div class="articlelist">
    <!-- 下拉刷新 -->
    <van-pull-refresh
      v-model="isLoading"
      success-text="刷新成功"
      @refresh="onRefresh"
    >
      <!-- 上拉加载更多 -->
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多数据了"
        @load="onLoad"
        offset="10"
        :immediate-check="false"
      >
        <article-item
          v-for="obj in articleList"
          :key="obj.art_id"
          :obj="obj"
          @dislike="disLikeArticle"
        />
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticleListApi } from "@/api/home";
export default {
  name: "ArticleList",
  props: {
    channel: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      timestamp: Date.now(),
      // 文章列表
      articleList: [],
      // 控制每一页的加载状态，控制下拉刷新状态
      loading: false,
      // 控制整个列表的加载状态
      finished: false,
      isLoading: false,
    };
  },
  created() {
    this.getArticleList();
  },
  methods: {
    // 获取文章列表
    async getArticleList(Pullup) {
      const resp = await getArticleListApi(this.channel.id, this.timestamp);
      console.log(resp);
      const { pre_timestamp, results } = resp.data;
      // 如果后台返回的results长度为零或者pre_pre_timestamp的值为nulL，说明无更多数据了
      if (!results || !pre_timestamp) {
        // 整个列表加载结束
        this.finished = true;
        return;
      }
      // 保存文章列表 上拉旧新合并，下拉新旧合并
      this.articleList = Pullup
        ? [...this.articleList, ...results]
        : [...results, ...this.articleList];
      // 保存前一页返回的时间戳
      this.timestamp = pre_timestamp;
      this.loading = false;
      this.isLoading = false;
    },
    // 上拉加载
    onLoad() {
      this.getArticleList(true);
    },
    // 下拉刷新
    onRefresh() {
      // console.log("下拉了");
      this.getArticleList(false);
    },
    // 删除不喜欢文章
    disLikeArticle(id) {
      const idx = this.articleList.findIndex((item) => item.art_id === id);
      if (idx != -1) {
        this.articleList.splice(idx, 1);
        // 数组长度小于10，不够删了
        if (this.articleList.length < 7) {
          this.getArticleList(true);
        }
      }
    },
  },
};
</script>

<style scoped>
.articlelist {
  height: calc(100vh - 138px);
  overflow-y: scroll;
}
</style>